package com.Jano.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: CrossDomainInterceptor 解决跨域 复杂请求 cookie 请求头<br>
 * date: 2022/7/10 9:08 PM <br>
 * author: zoumaoji <br>
 * version: 1.0 <br>
 *  拦截所有的请求
 */
@Component
public class CrossDomainInterceptor implements HandlerInterceptor {
    /**
     * 处理器方法执行之前的操作
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  处理器及其方法对象
     * @return 如果为true则继续执行后续的拦截器和控制器方法，否则不执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入了拦截器");
        //cookie携带的跨域解决
        response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //请求方法的跨域解决
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT,PATCH");
        response.setHeader("Access-Control-Max-Age", "0");
        //请求头的跨域解决 （解决响应的自定义Header前端无法读取的情况,在后面解决）
        //暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
        /**response.setHeader("Access-Control-Expose-Headers", "你自定义的响应头字段名");*/
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("XDomainRequestAllowed", "1");
        //对预检请求的放行
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(200);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
